package com.itlong.cloud.controller.appreciation;

import com.itlong.cloud.POJO.DTO.property.PropertyProjectUpdateArrearageLinkageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyArrearageBillGetVO;
import com.itlong.cloud.POJO.VO.property.PropertyArrearageLinkageVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.iottp.IIotTpJPushClientServiceClient;
import com.itlong.cloud.project.property.IPropertyAccountServiceClient;
import com.itlong.cloud.project.property.IPropertyArrearageLinkageServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 * 物业系统欠费联动设置模块聚合Controller。
 * </desc>
 *
 * @createDate 2019/01/22
 */
@RestController
@RequestMapping(path = "/arrearage/linkage")
public class PropertyArrearageLinkageController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(PropertyArrearageLinkageController.class);

    @Autowired
    IPropertyArrearageLinkageServiceClient iPropertyArrearageLinkageServiceClient;

    //极光推送国内
    @Autowired
    IIotTpJPushClientServiceClient iIotTpJPushClientServiceClient;

    @Autowired
    private IPropertyAccountServiceClient iPropertyAccountServiceClient;

    private static ExecutorService jPushThreadPool = Executors.newFixedThreadPool(5); // 同步数据线程池


    /**
     * <desc>
     * 获取欠费联动设置信息
     * <desc/>
     *
     * @param projectId 项目编号
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/01/22
     */
    @RequestMapping(path = "/getArrearageLinkageInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object getArrearageLinkageInfo(String projectId) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            if (StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iPropertyArrearageLinkageServiceClient.getArrearageLinkageInfo(projectId));
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_欠费联动设置_获取欠费联动设置信息】查询未缴费信息失败"), e);
        }
    }

    /**
     * <desc>
     * 更新欠费联动信息
     * <desc/>
     *
     * @param dto1 欠费联动信息
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/01/22
     */
//    @RequestMapping(path = "/updateArrearageLinkageInfo", method = RequestMethod.POST)
//    @LoggerInfo(operateDesc = LogDescConstant.ARREARAGE_LINKAGE_UPDATE_LOG_DESC)
//    @ResponseBody
    public Object updateArrearageLinkageInfo(PropertyProjectUpdateArrearageLinkageDTO dto1) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto1 = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectUpdateArrearageLinkageDTO.class, request);
            PropertyProjectUpdateArrearageLinkageDTO dto = dto1;
            if (StringUtils.isBlank(dto.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getAppFunctionLimit())) {//app功能限制:0关闭,1开启
                return new MessageVO(PropertyErrorCodeEnum.APP_FUNCTION_LIMIT_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getArrearageDeviceDate())) {//欠费设备联动生效时间(天)
                return new MessageVO(PropertyErrorCodeEnum.ARREARAGE_DEVICE_DATE_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getElevatorFaceLimit())) {//云电梯人脸限制:0关闭,1开启
                return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_FACE_LIMIT_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getIntercomFaceLimit())) {//云对讲人脸限制:0关闭,1开启
                return new MessageVO(PropertyErrorCodeEnum.INTERCOM_FACE_LIMIT_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getIntercomVisitorLimit())) {//云对讲访客限制:0关闭,1开启
                return new MessageVO(PropertyErrorCodeEnum.INTERCOM_VISITOR_LIMIT_EMPTY_ERR.getErrorCode());
            }
            PropertyArrearageLinkageVO propertyArrearageLinkageVO = iPropertyArrearageLinkageServiceClient.updateArrearageLinkageInfo(dto);
            //app功能限制变更发送极光推送
            if (propertyArrearageLinkageVO != null && !propertyArrearageLinkageVO.getAppFunctionLimit().equals(dto.getAppFunctionLimit())) {
                Map<String, String> comands = new HashMap<>();
                comands.put("refreshSips", "1");
                List<String> list = iPropertyArrearageLinkageServiceClient.getArrearagePhoneNum(dto.getProjectId());
                jPushThreadPool.execute(() -> {
                    for (String phoneNum : list) {
                        try {
                            iIotTpJPushClientServiceClient.pushWithTaskTO(dto.getProjectId(), phoneNum, comands, "欠费联动app功能限制变更");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            //修改了过期时间需要重新计算,并极光推送
            if (propertyArrearageLinkageVO != null && !propertyArrearageLinkageVO.getArrearageDeviceDate().equals(dto.getArrearageDeviceDate())) {
                List<PropertyArrearageBillGetVO> propertyArrearageBillGetVOList = iPropertyAccountServiceClient.statisticsPenaltyForProperty(dto.getProjectId());
                if (propertyArrearageBillGetVOList != null && !propertyArrearageBillGetVOList.isEmpty()) {
                    jPushThreadPool.execute(() -> {
                        List<String> alreadyPushed = new ArrayList<>();
                        Map<String, String> comands = new HashMap<>();
                        comands.put("refreshSips", "1");
                        for (PropertyArrearageBillGetVO propertyArrearageBillGetVO : propertyArrearageBillGetVOList) {
                            String projectIdAndPhone = propertyArrearageBillGetVO.getProjectId() + "," + propertyArrearageBillGetVO.getPhoneNum();
                            if (!alreadyPushed.contains(projectIdAndPhone)) {
                                try {
                                    iIotTpJPushClientServiceClient.pushWithTaskTO(propertyArrearageBillGetVO.getProjectId(), propertyArrearageBillGetVO.getPhoneNum(), comands, "欠费联动app功能限制变更");
                                    alreadyPushed.add(projectIdAndPhone);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                }
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), "");
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_欠费联动_欠费联动设置】欠费联动设置失败"), e);
        }
    }
}